package com.yohann.algorithm;

/**
 * <p>
 * 插值查找
 * </p>
 *
 * @author Yohann
 * @since 2020/12/31 13:23
 */
public class InsertValueSearch {
    public static void main(String[] args) {
        int[] arr = new int[100];
        for (int i = 0; i < 100; i++) {
            arr[i] = i;
        }

        System.out.println(insertValueSearch(arr, 0, arr.length - 1, 0));
    }

    /**
     * 插值查找
     *
     * @param arr    查找数组
     * @param left   左索引
     * @param right  索引
     * @param target 目标值
     * @return 目标索引（不存在返回-1）
     */
    public static int insertValueSearch(int[] arr, int left, int right, int target) {
        //避免越界
        if (left > right || target < arr[0] || target > arr[arr.length - 1]) {
            return -1;
        }

        //求出middle
        int middle = left + (right - left) * (target - arr[left]) / (arr[right] - left);
        int midVal = arr[middle];

        if (target > midVal) {
            //向右递归
            return insertValueSearch(arr, middle + 1, right, target);
        }

        if (target < midVal) {
            //向左递归
            return insertValueSearch(arr, left, middle - 1, target);
        }

        return middle;
    }
}